package com.chushouya.manager.service.admin.impl;

import cn.hutool.core.util.IdUtil;
import com.chushouya.manager.dto.admin.partner.*;
import com.general.framework.core.enums.StatusEnum;
import com.general.framework.core.lang.*;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.redis.RedisCache;
import com.chushouya.manager.constants.ClerkStatusEnum;
import com.chushouya.manager.constants.PartnerStatusEnum;
import com.chushouya.manager.constants.PartnerTypeEnum;
import com.chushouya.manager.dao.entity.PartnerEntity;
import com.chushouya.manager.dao.repository.PartnerRepository;
//=====manager.dto.admin.partner.*;
import com.chushouya.manager.dto.admin.partner.*;
import com.chushouya.manager.service.admin.AdminUserService;
import com.chushouya.manager.service.admin.PartnerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class PartnerServiceImpl implements PartnerService {

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private PartnerRepository partnerRepository;


    @Resource
    private RedisCache redisCache;

    private static final String partnerCacheKey = "PartnerCache:{}";

    @Override
    public PageResult<PartnerListDTO> selectPage(PartnerQuery query) {
        PageResult<PartnerEntity> page = partnerRepository.selectPageResult(query);
        PageResult<PartnerListDTO> pageResult = PageResult.of(page, PartnerListDTO.class);
        partnerList(pageResult.getRows());
        return pageResult;
    }

    /**
     * 处理合作商列表
     */
    private void partnerList(List<PartnerListDTO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        for (PartnerListDTO dto : list) {
            dto.setHasRules(Numbers.INTEGER_ZERO);
            dto.setHasRatio(Numbers.INTEGER_ZERO);
        }
    }

    @Override
    public PartnerDetailDTO detail(Long partnerId) {
        PartnerEntity partnerEntity = selectByPrimaryKey(partnerId);

        return Beans.copy(partnerEntity, PartnerDetailDTO.class);
    }
    private PartnerEntity selectByPrimaryKey(Long id) {
        Validate.isNull(id, "合作商Id不能为空");
        PartnerEntity partnerEntity = partnerRepository.selectByPrimaryKey(id);
        Validate.isNull(partnerEntity, "合作商不存在");
        return partnerEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(PartnerSaveDTO dto) {
        PartnerEntity partnerEntity = Beans.copy(dto, PartnerEntity.class);
        String partnerData = Strings.format("{},{},{}", Jsons.toJSONString(dto), Dates.getDateNowStr(),IdUtil.getSnowflakeNextId());
        partnerEntity.setAppKey(Base64.encodeBase64String(DigestUtils.md5Hex(partnerData).getBytes()));
        partnerRepository.insertSelective(partnerEntity);

    }

    @Override
    public void remove(Long partnerId) {
        Validate.isNull(partnerId, "合作商Id不能为空");
        partnerRepository.deleteByPrimaryKey(partnerId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PartnerUpdateDTO dto) {
        PartnerEntity partnerEntity = partnerRepository.selectByPrimaryKey(dto.getPartnerId());
        PartnerEntity update = Beans.copy(dto, PartnerEntity.class);
//        if (Objects.equals(PartnerTypeEnum.partner.value(), dto.getPartnerType()) && Longs.isNullOrZero(partnerEntity.getAdminUserId())) {
//            Validate.isNull(dto.getContactUser(), "联系人不能为空");
//            Validate.isNull(dto.getContactPhone(), "联系电话不能为空");
//            Check.mobile(dto.getContactPhone(), "联系电话格式不正确");
//            this.refreshPartnerCache();
//        }
        partnerRepository.updateByPrimaryKeySelective(update);
    }

    @Override
    public Boolean switchStatus(Long partnerId) {
        PartnerEntity partnerEntity = selectByPrimaryKey(partnerId);
        Integer status = Objects.equals(ClerkStatusEnum.enable.value() , partnerEntity.getStatus()) ? PartnerStatusEnum.disable.value() : PartnerStatusEnum.enable.value();
        partnerEntity = new PartnerEntity();
        partnerEntity.setPartnerId(partnerId);
        partnerEntity.setStatus(status);
        partnerRepository.updateByPrimaryKeySelective(partnerEntity);
        return Objects.equals(PartnerStatusEnum.enable.value() , partnerEntity.getStatus());
    }

    @Override
    public String getPartnerName(Long partnerId) {
        return this.selectByPrimaryKey(partnerId).getPartnerName();
    }

    @Override
    public List<PartnerSimpleDTO> selectList(PartnerQuery query) {
        return Beans.copyList(partnerRepository.selectList(query), PartnerSimpleDTO.class);
    }


    @Override
    public void refreshPartnerCache() {
        this.initPartnerData();
    }


    private void initPartnerData() {
        log.info("====>开始初始化合作商数据");
        redisCache.keys(Strings.format(partnerCacheKey, "*")).forEach(key->{
            redisCache.deleteObject(key);
        });
        PartnerQuery query = new PartnerQuery();
        query.setStatus(StatusEnum.normal.value());
        query.setPartnerType(PartnerTypeEnum.partner.value());
        final List<PartnerEntity> allPartner = partnerRepository.selectList(query);
        for (PartnerEntity partner : allPartner) {
            if (Objects.equals(partner.getPartnerType(), PartnerTypeEnum.partner.value())) {
                final String key = Strings.format(partnerCacheKey, partner.getPartnerId());
                redisCache.setCacheObject(key, Beans.copy(partner, PartnerSimpleDTO.class));
            }
        }
        log.info("====>初始化合作商数据完成");
    }

}
